package javao.cn.modules.oss.controller;

import javao.cn.common.exception.ServiceException;
import javao.cn.common.utils.PageUtils;
import javao.cn.common.utils.R;
import javao.cn.modules.oss.entity.SysOssEntity;
import javao.cn.modules.oss.service.SysOssService;
import javao.cn.modules.sys.service.SysConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传
 *
 * @author
 */
@RestController
@RequestMapping("sys/oss")
public class SysOssController {
	@Autowired
	private SysOssService sysOssService;

    @Autowired
    private SysConfigService sysConfigService;

	
	/**
	 * 列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:oss:all")
	public R list(@RequestParam Map<String, Object> params){
		PageUtils page = sysOssService.queryPage(params);

		return R.ok().put("page", page);
	}



	/**
	 * 本地保存路径
	 */
	@Value("${file.path}")
	private String dirPath;

	/**
	 * 上传文件
	 */
	@PostMapping("/upload")
	@RequiresPermissions("sys:oss:all")
	public R upload(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			throw new ServiceException("上传文件不能为空");
		}
		InputStream inputStream = file.getInputStream();
		// 创建 upload 目录（如果不存在）
		Path uploadPath = Paths.get(dirPath);
		Files.createDirectories(uploadPath);

		//文件后缀
		String prefix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		String fileName = UUID.randomUUID() + prefix;
		Files.copy(inputStream,new File(dirPath + fileName).toPath(), StandardCopyOption.REPLACE_EXISTING);
		//拼接上传文件路径
		String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
				.path("/"+fileName)
				.toUriString();
		// 保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(fileDownloadUri);
		ossEntity.setCreateDate(new Date());
		sysOssService.save(ossEntity);
		return R.ok().put("url", fileDownloadUri);
	}


	/**
	 * 删除
	 */
	@PostMapping("/delete")
	@RequiresPermissions("sys:oss:all")
	public R delete(@RequestBody Long[] ids){
		sysOssService.removeByIds(Arrays.asList(ids));

		return R.ok();
	}

}
